#include "..\Shared\Command.h"
#include <Windows.h>
#include <stdio.h>

Container<Value>::Container()
{
	Objects = NULL;
	Count = 0;
	Ref++;
	if(Ref == 1)
		Error = new Value("Error","Error");
	Parent = NULL;
}

Value &Container<Value>::operator[] (const Value &Index) const
{
	if(Index.GetType() == AT_INT)
	{
		if(Index.ToInt() >= 0 && Index.ToInt() < Count)
			return *Objects[Index.ToInt()];
	}
	else if(Index.GetType() == AT_STRING)
	{
		for(int i = 0; i < Count; i++)
			if(strcmp(Objects[i]->name, Index.ToCharPtr()) == 0)
				return *Objects[i];
	}
	return *Error;
}

Container<Value> SpiltString(const Value& String, const char *Delims)
{
	Container<Value> Return;

	std::string Buffer = String.ToCharPtr();
	int Pos = 0;
	std::string TempStr;
	Pos = Buffer.find(Delims);
	while(Pos != std::string::npos)
	{
		TempStr = Buffer.substr(0, Pos);
		Buffer = Buffer.substr(Pos + 1, Buffer.length() - Pos);
		Return.Add(TempStr.c_str());
		Pos = Buffer.find(Delims);
	}

	Return.Add(Buffer.c_str());

	return Return;
}

Command::Command()
{
	//memset(plugin, 0, PLUGINNAMELEN);
	name = "";
}

Command::Command(const Command &Source)
{
	Copy(Source);
}

Command::~Command()
{
}

Command & Command::operator = (const Command &Source)
{
	Copy(Source);

	return *this;
}

Value Command::ToSendableString()
{
	Value Return;

	Return = "Command Name:";
	Return += name;
	Return += "\n";
	Return += "Arguments:";
	Return += Arguments.Size();
	Return += "\n{\n";
	for(int i = 0; i<Arguments.Size(); i++)
	{
		Return += "\t";
		Return += Arguments[i].ToSendableString();
		Return += "\n";
	}
	Return += "}\nReturns:";
	Return += Returns.Size();
	Return += "\n{\n";
	for(int i = 0; i<Returns.Size(); i++)
	{
		Return += "\t";
		Return += Returns[i].ToSendableString();
		Return += "\n";
	}
	Return += "}\n";
	return Return;
}

void Command::SetFromSendableString(Value &String)
{
	Container<Value> Spilt = SpiltString(String, "\n");
	Container<Value> Elements;
	for(int i = 0; i < Spilt.Size(); ++i)
	{
		Elements = SpiltString(Spilt[i],":");
		if(Elements[0] == "Command Name")
			name = Elements[1];
		else if(Elements[0] == "Arguments")
		{
			i += 2;
			Arguments.Clear();
			for(int j = 0; j < atoi(Elements[1].ToCharPtr()) ; ++j)
			{
				Arguments.Add("");
				if(Spilt[i].ToCharPtr()[0] == '\n')
				Arguments[j].SetFromSendable(((char*)Spilt[i].ToCharPtr())+1);
				else
					Arguments[j].SetFromSendable(((char*)Spilt[i].ToCharPtr()));
				i++;
			}
		}
		else if(Elements[0] == "Returns")
		{
			i+=2;
			Returns.Clear();
			for(int j = 0; j < atoi(Elements[1].ToCharPtr()); ++j)
			{
				Returns.Add("");
				Returns[j].SetFromSendable(((char*)Spilt[i].ToCharPtr())+1);
				i++;
			}
		}
	}
}

void Command::Copy(const Command &Source)
{
	//memcpy(plugin, Source.plugin, PLUGINNAMELEN);
	name = Source.name;
	Arguments = Source.Arguments;
}